package com.atguigu.springcloud.alibaba.Ib;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLB implements LoadBalancer {

    // 初始值
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    // 获取 rest 接口第几次请求数
    public final int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get(); // 获取当前值，默认0
            next = current >= 2147483647 ? 0 : current + 1; // Integer.MAX_VALUE：2147483647
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("*******第几次访问,次数next:" + next);
        return next;
    }

    /**
     * 负载均衡算法
     * @param serviceInstances 服务器集群
     * @return
     */
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        // 获取下标
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
